package com.ruoyi.server.MQTT.listener;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class MqttHandler implements MqttCallback {
    public static final String MAIN_TOPIC = "zack/main/";//主通道头
    public static final String SON_TOPIC = "zack/son/";//子通道头
    public static final String TOPIC_REQUEST = "request";//发送尾
    public static final String TOPIC_RESPONSE = "response";//接收尾
    public static final int QOS_0 = 0;//接收尾
    
    
    
    public static final String MAIN_TOPIC_RESPONSE = MAIN_TOPIC + TOPIC_RESPONSE; //主通道接收
    public static final String SON_TOPIC_RESPONSE = SON_TOPIC + "+/" + TOPIC_RESPONSE; // 子通道接收
    
    @Autowired
    private MqttClient mqttClient;
    
    @PostConstruct
    public void init() throws MqttException {
        mqttClient.setCallback(this);
        String[] strings = {MAIN_TOPIC_RESPONSE,SON_TOPIC_RESPONSE};
        int[] ints = {QOS_0,QOS_0};
        mqttClient.subscribe(strings, ints); // 订阅通配符主题[8](@ref)
    }
    
    @Override
    public void connectionLost(Throwable throwable) {
    
    }
    
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info("收到消息 - Topic: {}, Payload: {}", topic, new String(message.getPayload()));
    }
    
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    
    }
    
    // 发布消息工具方法
    public void publish(String topic, String payload, int qos) throws MqttException {
        MqttMessage msg = new MqttMessage(payload.getBytes());
        msg.setQos(qos);
        msg.setRetained(true); // 保留消息[2](@ref)
        mqttClient.publish(topic, msg);
    }

}
